package com.sihai.ehr.web.action.sign;

import com.sihai.core.LimitedList;
import com.sihai.core.beans.BeanInject;
import com.sihai.ehr.model.biz.*;
import com.sihai.ehr.model.sys.AuditStatus;
import com.sihai.ehr.model.sys.Organization;
import com.sihai.ehr.model.sys.User;
import com.sihai.ehr.service.AdministrationEvectionApplyFormService;
import com.sihai.ehr.service.EmployeeService;
import com.sihai.ehr.service.UserService;
import com.sihai.ehr.utils.DateUtil;
import com.sihai.ehr.web.action.EHRAction;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.xwork.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * author: wxn
 * since: 13-4-14 下午12:32
 * 行政签核系统 - 出差申请单Action
 */
@Results({
        @Result(name = "list", location = "/WEB-INF/pages/sign/administration_evection_apply_form_list.jsp"),
        @Result(name = "add", location = "/WEB-INF/pages/sign/administration_evection_apply_form_input.jsp"),
        @Result(name = "audit", location = "administration_evection_apply_form_audit.jsp")
})
public class AdministrationEvectionApplyFormAction extends SignBaseAction {
    @BeanInject
    private AdministrationEvectionApplyFormService administrationEvectionApplyFormService;
    @BeanInject
    private EmployeeService employeeService;
    @BeanInject
    private UserService userService;

    private LimitedList<AdministrationEvectionApplyForm> applyForms;
    private AdministrationEvectionApplyForm applyForm;

    private List<List<AdministrationEvectionApplyFormAuditing>> audits;

    private List<HelpDepartment> helpDepartmentList;

    @Action("/public/administration-evection-apply-form")
    public String listByUser() throws Exception {
        userType = 2;
        String temp = execute();
        showChildOrg = false;
        return temp;
    }

    @Action("/sign/administration-evection-apply-form")
    @Override
    public String execute() throws Exception {
        showChildOrg = true;
        init();
        User user = null;
        if(userType == 2){
            user = userService.getUser(getCurrentUserId());
        }
        applyForms = administrationEvectionApplyFormService.findAdministrationEvectionApplyForm(user, searchFormPojo, createLimit(), createSorter());
        this.paging(applyForms);
        this.setPageUrl(userType==1 ? "sign/administration-evection-apply-form.xhtml" : "public/administration-evection-apply-form.xhtml");
        return "list";
    }

    @Action("/public/administration-evection-apply-form-input")
    public String toAddByUser() throws Exception {
        userType = 2;
        return toAdd();
    }

    @Action("/sign/administration-evection-apply-form-input")
    public String toAdd() throws Exception {
        HttpSession session = ServletActionContext.getRequest().getSession();
        if(StringUtils.isNotBlank(getParameter("choice"))){
            Object obj = session.getAttribute("choice_help_department_list");
            if(obj != null){
                helpDepartmentList = (List<HelpDepartment>)obj;
                session.removeAttribute("choice_help_department_list");
            }
        }

        Object obj = session.getAttribute("current_apply_form");
        if(obj != null){
            applyForm = (AdministrationEvectionApplyForm)obj;
            session.removeAttribute("current_apply_form");
        }
        return "add";
    }

    @Action("/public/administration-evection-apply-form-save")
    public String saveByUser() throws Exception {
        userType = 2;
        return save();
    }

    //保存
    @Action("/sign/administration-evection-apply-form-save")
    public String save() throws Exception {
        String[] helpDepartmentDatas = getParameterValues("help_department");
        if(helpDepartmentDatas == null || helpDepartmentDatas.length == 0){
            return execute();
        }
        List<HelpDepartment> list = new ArrayList<HelpDepartment>(helpDepartmentDatas.length);
        for(String temp : helpDepartmentDatas){
            String[] datas = StringUtils.split(temp, "-", 3);
            HelpDepartment department = new HelpDepartment();
            Organization o = new Organization();
            o.setId(NumberUtils.createLong(datas[0]));
            o.setFullName(datas[1]);
            department.setOrganization(o);
            department.setContent(datas[2]);
            list.add(department);
        }
        if(list == null || list.isEmpty()){
            return execute();
        }

        if(applyForm != null){
            Long userId = getCurrentUserId();
            EmployeeinfoWork work = null;
            if(userId > 0){
                User user = userService.getUser(userId);
                if(user != null){
                    work = user.getWork();
                }
            }
            Date startDate = DateUtil.createDate(getParameter("s_evectionStartDate"), "yyyy-MM-dd");
            Date endDate = DateUtil.createDate(getParameter("s_evectionEndDate"), "yyyy-MM-dd");
            applyForm.setStatus(AuditStatus.wait_audit);
            applyForm.setWork(work); //如果是超级管理员操作，则work为null
            applyForm.setEvectionStartDate(startDate);
            applyForm.setEvectionEndDate(endDate);
            applyForm.setDepartments(list);
            administrationEvectionApplyFormService.save(applyForm);
        }
        return execute();
    }

    //保存到session
    @Action(value = "/ajax/administration-evection-apply-form-save", results = {@Result(name = "success", type = "json", params = {"root", "result"})})
    public String saveToSession() throws Exception {
        String startDateStr = getParameter("s_evectionStartDate");
        if(StringUtils.isNotBlank(startDateStr)){
            Date startDate = DateUtil.createDate(startDateStr, "yyyy-MM-dd");
            if(applyForm == null){
                applyForm = new AdministrationEvectionApplyForm();
            }
            applyForm.setEvectionStartDate(startDate);
        }

        String endDateStr = getParameter("s_evectionEndDate");
        if(StringUtils.isNotBlank(endDateStr)){
            Date endDate = DateUtil.createDate(endDateStr, "yyyy-MM-dd");
            if(applyForm == null){
                applyForm = new AdministrationEvectionApplyForm();
            }
            applyForm.setEvectionEndDate(endDate);
        }
        ServletActionContext.getRequest().getSession().setAttribute("current_apply_form", applyForm);
        return SUCCESS;
    }

    @Action("/sign/administration-evection-apply-form-audit")
    public String toAudit() throws Exception {
        //得到审核对象
        if(applyForm == null || applyForm.getId() == null){
            return execute();
        }
        applyForm = administrationEvectionApplyFormService.get(applyForm.getId());

        //得到当前审核历史记录(没有就先保存一个审核流程次数)
        audits = administrationEvectionApplyFormService.findAdministrationEvectionApplyFormAuditing(applyForm.getId());
        if(audits == null || audits.isEmpty()){
            administrationEvectionApplyFormService.saveAdministrationEvectionApplyFormAuditingProcess(applyForm.getId());
            audits = administrationEvectionApplyFormService.findAdministrationEvectionApplyFormAuditing(applyForm.getId());
        }
        //检查当前登录用户是否可以审核当前结点
        if(applyForm.getWork() != null && audits != null && !audits.isEmpty()){
            checkCanAudit(applyForm.getWork().getDuty(), audits.get(audits.size()-1));
        }
        currentAuditType = AuditType.audit_administration_evection_apply_form.toString();

        return "audit";
    }

    public AdministrationEvectionApplyForm getApplyForm() {
        return applyForm;
    }

    public void setApplyForm(AdministrationEvectionApplyForm applyForm) {
        this.applyForm = applyForm;
    }

    public LimitedList<AdministrationEvectionApplyForm> getApplyForms() {
        return applyForms;
    }

    public List<List<AdministrationEvectionApplyFormAuditing>> getAudits() {
        return audits;
    }

    public List<HelpDepartment> getHelpDepartmentList() {
        return helpDepartmentList;
    }
}
